package com.itheima.service.impl;

import com.itheima.anno.MyLog;
import com.itheima.mapper.DeptLogMapper;
import com.itheima.mapper.DeptMapper;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.Dept;
import com.itheima.pojo.DeptLog;
import com.itheima.service.DeptLogService;
import com.itheima.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;


@Service
public class DeptImpl implements DeptService {
    @Autowired
    private DeptMapper deptMapper;

    @Autowired
    private EmpMapper empMapper;

    @Autowired
    private DeptLogService deptLogService;

    @Override
    public List<Dept> select() {
        return deptMapper.select();
    }

    @Override
    @Transactional(rollbackFor = Exception.class) //当前方法添加了事务管理
    @MyLog
    public void delete(Integer id) throws Exception{
        try {
            //根据部门id删除部门信息
            deptMapper.delete(id);

            //模拟异常发生
            /*if (true){
                throw new Exception("出现异常了~~~");
            }*/
            //删除部门下的所有员工信息
            empMapper.deleteByDeptId(id);
        }  finally {
            //记录操作日志
            DeptLog deptLog = new DeptLog();
            deptLog.setCreateTime(LocalDateTime.now());
            deptLog.setDescription("删除部门"+id);
            deptLogService.insert(deptLog);
        }
    }

    @MyLog
    @Override
    public void insert(Dept dept) {
        dept.setCreateTime(LocalDateTime.now());
        dept.setUpdateTime(LocalDateTime.now());
        deptMapper.insert(dept);
    }

    @MyLog
    @Override
    public void update(Integer id, String name) {
        Dept dept = deptMapper.selectByid(id);
        deptMapper.update(id, name);
    }

    @Override
    public Dept selectById(Integer id) {
        return deptMapper.selectByid(id);
    }
}
